package com.chengww.grab_rp.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.chengww.grab_rp.R
import com.chengww.grab_rp.activities.LoginActivity


/**
 * Created by chengww on 2/21/21
 * @author chengww
 */
class MainService : Service() {
    private var receiver: GrabBroadcastReceiver? = null

    override fun onCreate() {
        super.onCreate()
        val mNM = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var mNotificationChannel = mNM.getNotificationChannel(CHANNEL_ID)
            if (mNotificationChannel == null) {
                mNotificationChannel = NotificationChannel(
                    CHANNEL_ID,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                mNotificationChannel.description = getString(R.string.app_name)
                mNM.createNotificationChannel(mNotificationChannel)
            }
        }
        val nb = NotificationCompat.Builder(this, CHANNEL_ID)
        nb.setContentTitle(getString(R.string.app_name))
            .setTicker(getString(R.string.app_name))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("抢红包服务正在运行")
            .setWhen(System.currentTimeMillis())
        val notification = nb.build()
        val intent = Intent(applicationContext, LoginActivity::class.java)
        val sender = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        notification.contentIntent = sender
        startForeground(1, notification)

        if (receiver == null) {
            receiver = GrabBroadcastReceiver()
            val filter = IntentFilter()
            filter.addAction(INTENT_ACTION_PLUGIN)
            registerReceiver(receiver, filter, GrabBroadcastReceiver.PERMISSION, null)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        return START_NOT_STICKY
    }


    override fun onDestroy() {
        receiver?.let { unregisterReceiver(it) }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    companion object {
        private const val CHANNEL_ID = "抢红包通知"
        private const val INTENT_ACTION_PLUGIN = "com.chengww.grab_rp.plugin"
    }
}